<template>
  <div class="city-select">
    <el-cascader
      v-model="selectedCity"
      :options="cityOptions"
      :props="cascader"
      @change="handleChange"
      placeholder="请选择城市"
      clearable
      :class="{ 'is-error': isError }"
    />
  </div>
</template>

<script setup name="CitySelectBox">
import { ref, watch } from 'vue';
import { cityData } from './city-data';

const emit = defineEmits(['update:modelValue', 'cityChange', 'cityValue']);
const props = defineProps({
  modelValue: String,
  isError: {
    type: Boolean,
    default: false,
  },
});

const selectedCity = ref('');
const cityOptions = ref(cityData);

// 配置级联选择器的属性
const cascader = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true,
  emitPath: true,
};

// 处理选择变化
const handleChange = (value) => {
  emit('cityValue', value);
  if (value && value.length > 0) {
    const province = value[0];
    emit('update:modelValue', value[value.length - 1]);
    emit('cityChange', {
      city: value[value.length - 1],
      province: province,
    });
  } else {
    emit('update:modelValue', '');
    emit('cityChange', {
      city: '',
      province: '',
    });
  }
};

// 重置选择
const resetSelect = () => {
  selectedCity.value = '';
};

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    selectedCity.value = newVal;
  }
);

// 暴露方法给父组件
defineExpose({
  resetSelect,
});
</script>

<style lang="scss" scoped>
.city-select {
  display: inline-block;
  width: 100%;

  :deep(.el-cascader) {
    width: 100%;
  }

  :deep(.el-cascader.is-error .el-input__wrapper) {
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
}
</style>
